package com.aaa.dao.impl;

import com.aaa.dao.MhallDao;
import com.aaa.entity.Mhall;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Controller
public class MhallDaoImpl implements MhallDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private RowMapper<Mhall> rowMapper=new RowMapper<Mhall>() {
        public Mhall mapRow(ResultSet resultSet, int i) throws SQLException {
            Mhall mhall=new Mhall();
            mhall.setId(resultSet.getLong("id"));
            mhall.setName(resultSet.getString("name"));
            mhall.setRow(resultSet.getString("row"));
            mhall.setLine(resultSet.getString("line"));
            mhall.setSeat(resultSet.getString("seat"));
            return mhall;
        }
    };
    public List<Mhall> listPage(String keyword, Integer offset, Integer limit) {
        String sql="select id,name,row,line,seat from mhall where name like ? order by id desc limit ?,?";
        List<Mhall> query = this.jdbcTemplate.query(sql, rowMapper, "%" + keyword + "%", offset, limit);
        return query;
    }

    public Integer count(String keyword) {
        String sql = "select count(id) as c from mhall where name like ? ";
        Integer result = this.jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getInt("c");
            }
        },"%"+keyword+"%");
        return  result;
    }

    public Integer save(Mhall mhall) {
        String sql="insert into mhall(name,row,line,seat) values(?,?,?,?)";
        int update = jdbcTemplate.update(sql,mhall.getName(),mhall.getRow(),mhall.getLine(),mhall.getSeat());
        return update;
    }

    public Integer update(Mhall mhall) {
        String sql="update mhall set name=?,row=?,line=?,seat=? where id=?";
        int update = jdbcTemplate.update(sql,mhall.getName(),mhall.getRow(),mhall.getLine(),mhall.getSeat(),mhall.getId());
        return update;
    }

    public Integer delete(Long id) {
        String sql="delete from mhall where id=?";
        int update = jdbcTemplate.update(sql,id);
        return update;
    }
}
